$(function(){
	
	asyncData.intialList();/*获取联系人*/
	button.mail_list();
	add.addteam();/*添加组*/
    add.newteam();
    bindEvent.newpage();
    bindEvent.checkall();
    bindEvent.saveteam();
    bindEvent.delet_people();
    bindEvent.export_list();
    bindEvent.import_list();
    bindEvent.find_people();

    
});
function GetQueryString(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
};/*获取地址栏URL*/
var asyncData={

	intialList:function(){
       $.getJSON("http://localhost:8080/contacts/contact/queryWithoutGroup",function(contacts){
       	render.initList(contacts);
         // 	var i=0;
       		// for(i=0;i<contacts.length;i++){
         //    $("table").append('<tr><td><input type="checkbox"></td>'
         //  	+'<td>'+contacts.contacts[i].name+'</td>'
         //  	+'<td>'+contacts.contacts[i].email+'</td>'
         //  	+'<td>'+contacts.contacts[i].tel+'</td>'
         //  	+'<td>'+contacts.contacts[i].group+'</td></tr>'
         //  	)};
       })
	}
};
var render={
	initList:function(contacts){     
			
     $.each(contacts.contacts,function(idx,item){
     	
     	$("table").append('<tr id="'+item.cid+'"><td><input type="checkbox"></td><td><a href="people_message.html?id='+item.cid+'">'+item.name+'</a></td><td><a href="people_message.html?id='+item.cid+'">'+item.email+'</td><td>'
     		+item.tel+'</a></td><td><a href="people_message.html?id='+item.cid+'">'+item.group+'</a></td></tr>');       	         
       })
	}
};
function myrefresh()
{
   window.location.reload();
}

var bindEvent={
	newpage:function(){
		$("#new_people").on("click",function(){
			    window.location.href="new_people.html";
		})
	},
	checkall:function(){
		$("#checkall").click(function(){
			if($("#checkall").prop("checked")==true){
			$("table tr td input:checkbox").prop("checked",true);
		}
		else{
			$("table tr td input:checkbox").prop("checked",false);
		}

		})
		

	},
	saveteam:function(){

		$("#save").on("click",function(){
			var team_name=$("#new_team").val();			
			$.post("http://localhost:8080/contacts/group/add",{
				data:team_name
			})
		})
	},
	delet_people:function(){
		$("#delete").on("click",function(){
			layer.open({
				style: 'width:60%;font-size:14px;',
				content: '确定删除联系人？',
				btn: ['确认', '取消'],
				shadeClose: false,
				btn1:function(){
					
			var cid={};
			var entriesArr=[];
			var tr=$(".table tr td input:checkbox:checked").parent().parent();
		for(var i = 0; i < tr.length; i++){
        var entryData = {
            cid:$(tr[i]).attr("id"),
        };
        entriesArr.push(entryData);
        }
        cid.manPlus=entriesArr;
			$.ajax({
        url: "http://localhost:8080/contacts/contact/delete",
        type: 'post',
        dataType: 'JSON',
        data:{"data": JSON.stringify(cid)},       
        success:function(data){
                   var text = data.result;
                  if(text==0){
                    alert("success");
                  }else{
                   alert("error");
                  }
                }
       

    });
           myrefresh();
				}
				
			})

		})		
},
import_list:function(){
 $("#submit").on("click",function(){
 	$("#file").click();
 });
	$("#file").change(function(){
		  // var elementIds=["flag"]; //flag为id、name属性名
    //     $.ajaxFileUpload({
    //         url: 'http://localhost:8080/contacts/import', 
    //         type: 'post',
    //         secureuri: false, //一般设置为false
    //         fileElementId: 'file', // 上传文件的id、name属性名
    //       //返回值类型，一般设置为json、application/json
    //         //传递参数到服务器
    //         success: function(data,status){  
    //         	 var json=eval('('+data+')');
    //             if(data.result==0){
    //                    alert("导入成功"+data.importQty)
    //             }
    //             else{
    //             	alert("导入失败")
    //             }
    //         },
           
    //     });
     var formData = new FormData($("#myform")[0]);  

		     $.ajax({  
		          url:'http://localhost:8080/contacts/import',  
		          type: 'POST',  
		          data: formData,
		          async: false,  
		          cache: false,  
		          contentType: false,  
		          processData: false,  
		          success: function (data) {  
		        	var json=eval('('+data+')');
		          	console.log(json);
		          	console.log(json.result);
		          	console.log(json.importQty);
		          	if(json.result==0){
		          			alert("成功导入"+json.importQty+"位联系人");
		   					myrefresh();
		          	}else if(json.result==1){

		          		alert("导入失败");

		          	}
		          },  
		          error: function (data) { 
		         	alert("导入失败");
		          }  
		 });  

	});	        
},
export_list:function(){
	$("#export").on("click",function(){
		$("#export_people").modal("toggle");
		$("#check_import").on("click",function(){
			var codeFormat=$(".modal-body .code input:checked").val();
			var fileFormat=$(".modal-body .file input:checked").val();
			var data={};
			data.codeFormat=codeFormat;
			data.fileFormat=fileFormat;
		$.ajax({
		url: "http://localhost:8080/contacts/export",
		type: 'post',
		// dataType: 'JSON',
		data:{"codeFormat":codeFormat,"fileFormat":fileFormat},
	    success:function(data){
		           var text = data.result;
		          if(text==0){
		          	 alert("导出成功");
		          }else{
		          	alert("导出失败");
		          }
		       	}
		// error:function(error){
		//        M_ContactsByCurriculumDesign.showConfirmModal("error","连接不上服务器！");
		//       }

	});
	window.location="http://localhost:8080/contacts/export?codeFormat="+codeFormat+"&fileFormat="+fileFormat ;
	


		})
	})
},
find_people:function(){
	$("#find_people").on("click",function(){
		var find_message=$("#find_message").val();
		$.ajax({
		url: "http://localhost:8080/contacts/contact/likeQuery",
		type: 'post',
		dataType: 'JSON',
		data:{"data":find_message},
	    success:function(contacts){
	    	var checkbox='<input type="checkbox">';
	    	$(".table table tr").remove();
	    	$(".table table").append('<tr id="checkall">\
          		<th>'+checkbox+'</th>\
          		<th>'+"姓名"+'</th>\
          		<th>'+"邮件地址"+'</th>\
          		<th>'+"手机号码"+'</th>\
          		<th>'+"所在分组"+'</th>\
          	</tr>');
		          $.each(contacts.contacts,function(idx,item){
	$("table").append('<tr id="'+item.cid+'"><td><input type="checkbox"></td><td><a href="people_message.html?id='+item.cid+'">'+item.name+'</a></td><td><a href="people_message.html?id='+item.cid+'">'+item.email+'</td><td>'
     		+item.tel+'</a></td><td><a href="people_message.html?id='+item.cid+'">'+item.group+'</a></td></tr>');  

		          })
		       	}
		// error:function(error){
		//        M_ContactsByCurriculumDesign.showConfirmModal("error","连接不上服务器！");
		//       }

	});
	})
}


};
var button={
	mail_list:function(){
		$("#mail_list").on("click",function(){
			window.location.href="index.html"
		})
	}
};
var add={
    addteam:function(){
        $("#add").on("click",function(){
            $("#mymodal").modal("toggle");
        })
    },
    newteam:function(){
    	     $("#team_list").append('<li><a href="group_list.html">'+"所有分组"+'</li>');
    	$.getJSON("http://localhost:8080/contacts/group/queryAll",function(groups){
    		        $.each(groups.groups,function(idx,item){
    		        	$("#team_list").append('<li><a href="group_people.html?id='+item.gid+'">'+item.groupName+'</li>');
    		        })
                   
    	})
         
        $("#save").on("click",function(){
            $("#team_list").append('<li>'+$("#new_team").val()+'</li>');
             $(".choose_select").append('<label>'+"<input type='checkbox'>"+$("#new_team").val()+'</label>');
        })
    }
};
	